const mongoose = require('mongoose');

const Router = require('koa-router');

const CommentRouter = new Router();

CommentRouter.post('/add', async (ctx) => {
  try {
    const CommentSchema = mongoose.model('Comment');
    const Comment = new CommentSchema(ctx.request.body);
    await Comment.save();
    ctx.body = {
      code: 200,
      message: '评论成功',
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

CommentRouter.get('/get', async(ctx) => {
  try {
    const CommentSchema = mongoose.model('Comment');
    const { goodsId } = ctx.request.query;
    // 根据关联的字段去查询，第二个参数是只显示headerImg字段
    const res = await CommentSchema.find({goodsId}).populate('userId', 'headerImg').sort({commentTime: -1}).exec();
    ctx.body = {
      code: 200,
      message: res,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

CommentRouter.delete('/delete', async (ctx) => {
  try {
    const { commentId } = ctx.request.query;
    const CommentSchema = mongoose.model('Comment');
    await CommentSchema.remove({_id: commentId});
    ctx.body = {
      code: 200,
      message: '删除成功',
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

module.exports = CommentRouter;